import 'dart:developer';

import 'package:get/get.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:sports_new/entity/my/help/help_entity.dart';
import 'package:sports_new/server/api/user_api.dart';
import 'package:sports_new/utils/toast_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';
import '../../../entity/other/image_upload_result_entity.dart';
import '../../../server/http/dio_utils.dart';
import '../../../utils/image_utils.dart';

class FeedbackLogic extends GetxController{
  List<String> uploadImages = [];
  final Rx<String> _str = "".obs;
  final Rx<String> _number = "".obs;
  final QuestionType questionType = Get.arguments;

  String get str => _str.value;
  String get number => _number.value;

  set number(String value) {
    _number.value = value;
    update();
  }
  set str(String value) {
    _str.value = value;
    update();
  }

  void addPhotoFromCamera(int type) async {
    final image = await ImageUtils.pickPhotoFromCamera();
    if (image == null) {return;}
    String path = image.path;
    if (type == 0) {
      final cropPath = await ImageUtils.cropImage(image.path);
      if (cropPath == null) {
        return;
      }
      path = cropPath;
    }
    List<ImageUploadResultEntity>? result =
    await DioUtils.uploadImage([path], 'feedback');
    if (result != null) {
      uploadImages.add(result.first.url ?? '');
    }
    update();
  }

  void addPhotoFromGallery(int type) async {
    List<AssetEntity> images = [];
    try {
      images = await ImageUtils.pickPhotoFromGallery(maxPhotos: 6) ?? [];
    }catch(e){
      log("---------${e}");
    }
    if (images.noValue) {
      return;
    }
    List<File> files = [];
    for (var data in images) {
      File? file = await data.file;
      if (file != null) {
        files.add(file);
      }
    }
    if (type == 0) {
      final cropPath = await ImageUtils.cropImage(files.first.path);
      if (cropPath == null) {
        return;
      }
      files = [File(cropPath)];
    }
    List<ImageUploadResultEntity>? result =
    await DioUtils.uploadImage(files.map((e) => e.path).toList(), 'feedback');
    if (result != null) {
      uploadImages.addAll(result.map((e) => e.url!));
      update();
    }
  }

  onDeleteImage(int index) {
    uploadImages.removeAt(index);
    update();
  }

  Future sendFeedback() async{
    var result = await UserApi.sendFeedback(
      type: questionType.id,
      images: uploadImages.join(","),
      suggest: questionType.info != null?""
        "${questionType.info}\n举报原因：${questionType.name}\n$str":
        str,
      wechat: number
    );
    if(result == 200){
      ToastUtils.show("反馈成功");
      Get.back();
    }else{
      ToastUtils.show("反馈失败,请再次尝试");
    }
  }
}